package com.example.zjsr.controller;

import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.zjsr.common.ServerResponse;
import com.example.zjsr.domain.*;
import com.example.zjsr.pojo.ilabresult.Step;
import com.example.zjsr.service.TmpU3dServer;
import com.example.zjsr.service.UserService;
import com.example.zjsr.service.impl.TmpU3dServerImpl;
import com.example.zjsr.util.JwtUtil;
import com.example.zjsr.util.OrdersId;
import com.example.zjsr.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * u3d调用接口
 */
@CrossOrigin
@RequestMapping(value = "/u3d")
@RestController
public class U3dController {


    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private OrdersId ordersId;

    @Autowired
    private UserService userService;

    @Autowired
    private TmpU3dServer tmpU3dServer;

    private Logger logger = LoggerFactory.getLogger(U3dController.class);


    /**
     * u3d发送请求模块场景状态（模块一、模块二、模块三），各个模块场景的状态
     *
     * @param request
     * @return
     */
    @PostMapping(value = "/sendU3dModule")
    public ServerResponse sendU3dModule(HttpServletRequest request, @RequestBody ModuleData moduleData) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        Integer module = moduleData.getModule();
        redisUtil.set(u.getId() + "module" + module, moduleData);//0为false，1为true
        return ServerResponse.createBySuccessMsg("发送成功");
    }


    /**
     * 获取到用户到u3d场景模块的第几个可以使用（有哪些参数）
     *
     * @param request
     * @param data
     * @return
     */
    @PostMapping(value = "/getU3dModule")
    public ServerResponse getU3dModule(HttpServletRequest request, @RequestBody String data) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        JSONObject jsonObject = JSON.parseObject(data);
        Integer module = jsonObject.getInteger("module");
        ModuleData moduleData = (ModuleData) redisUtil.get(u.getId() + "module" + module);//去获取u3d的场景模块的状态；存redis格式（用户编号+实验场景模块（1、2、3））
        if (null != moduleData) {
            return ServerResponse.createBySuccess(moduleData);
        } else {
            return ServerResponse.createByACCOUNTError("无该模块场景状态");
        }
    }


    /**
     * 前端发送水果种类名称
     *
     * @param request
     * @param data
     * @return
     */
    @PostMapping(value = "/sendFruitCategory")
    public ServerResponse sendFruitCategory(HttpServletRequest request, @RequestBody String data) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        JSONObject jsonObject = JSON.parseObject(data);
        String category = jsonObject.getString("category");
        redisUtil.set(u.getId() + "category", category);
        return ServerResponse.createBySuccessMsg("请求成功");
    }


    /**
     * 获取到前端选择的水果种类名称
     *
     * @param request
     * @return
     */
    @PostMapping(value = "/getFruitCategory")
    public ServerResponse getFruitCategory(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        String category = (String) redisUtil.get(u.getId() + "category");
        if (null != category) {
            return ServerResponse.createBySuccess(category);
        } else {
            return ServerResponse.createByACCOUNTError("水果还未选择！");
        }
    }

    /**
     * 前端发送直播参数设置
     *
     * @param request
     * @param productParameter
     * @return
     */
    @PostMapping(value = "/sendProductParameter")
    public ServerResponse sendProductParameter(HttpServletRequest request, @RequestBody ProductParameter productParameter) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        redisUtil.set(u.getId() + "productParameter", productParameter);//设置改用户的直播参数
        return ServerResponse.createBySuccessMsg("发送直播参数设置成功!");
    }


    /**
     * u3d获取直播参数
     *
     * @param request
     * @return
     */
    @PostMapping(value = "/getProductParameter")
    public ServerResponse getProductParameter(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        ProductParameter productParameter = (ProductParameter) redisUtil.get(u.getId() + "productParameter");
        if (StringUtils.isEmpty(productParameter)) {
            return ServerResponse.createByACCOUNTError("直播参数还未设置！");
        } else {
            return ServerResponse.createBySuccess(productParameter);
        }
    }


    /**
     * （场景二U3D传场景三U3D）场景设置：（score(分数)、category（模型名称）、x（模型坐标）、y（模型坐标）、z（模型坐标）
     * xRotaryInfo(旋转信息一)、yRotaryInfo(旋转信息二)、zRotaryInfo（旋转信息三））
     *
     * @param request
     * @param moduleParameter
     * @return
     */
    @PostMapping(value = "/sendSceneSetting")
    public ServerResponse sendSceneSetting(HttpServletRequest request, @RequestBody ModuleParameter moduleParameter) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        redisUtil.set(u.getId() + "moduleParameter", moduleParameter, 7200);
        return ServerResponse.createBySuccessMsg("场景设置成功！");
    }


    /**
     * 获取到场景参数（score(分数)、category（模型名称）、x（模型坐标）、y（模型坐标）、z（模型坐标）
     * xRotaryInfo(旋转信息一)、yRotaryInfo(旋转信息二)、zRotaryInfo（旋转信息三））
     *
     * @param request
     * @return
     */
    @PostMapping(value = "/getSceneSetting", produces = "application/json; charset=utf-8")
    public ServerResponse getSceneSetting(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        ModuleParameter moduleParameter = (ModuleParameter) redisUtil.get(u.getId() + "moduleParameter");//获取到场景参数信息
        if (StringUtils.isEmpty(moduleParameter)) {
            return ServerResponse.createByACCOUNTError("场景参数还未设置！");
        } else {
            return ServerResponse.createBySuccess(moduleParameter);
        }
    }

    /**
     * 添加直播方案
     *
     * @param request
     * @return
     */
    @PostMapping(value = "/addBroadcast")
    public ServerResponse addBroadcast(HttpServletRequest request, @RequestBody Broadcast broadcast) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        broadcast.setUserId(u.getId());
        return userService.addBroadcast(broadcast, u.getId());
    }


    /**
     * u3d获取到直播间方案设计
     *
     * @param request
     * @return
     */
    @PostMapping(value = "/getBroadcast")
    public ServerResponse getBroadcast(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        return userService.getBroadcast(u.getId());
    }


    /**
     * u3d提交直播中数据复盘数据
     *
     * @param request
     * @param analyseData
     * @return
     */
    @PostMapping(value = "/addAnalyseData")
    public ServerResponse addAnalyseData(HttpServletRequest request, @RequestBody AnalyseData analyseData) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        redisUtil.set(u.getId() + "analyseData", analyseData, 7200);
        return ServerResponse.createBySuccessMsg("成功提交直播中数据复盘数据");
    }

    @DeleteMapping(value = "/makeOrders")
    public ServerResponse makeOrders(HttpServletRequest request) {
        long orderId = ordersId.makeOrdersId();
        return ServerResponse.createBySuccess(Long.valueOf(orderId));
    }

    /**
     * U3D添加步骤模块(仪容仪表)
     *
     * @param request
     * @param
     * @return
     */
    @PostMapping(value = "/addScorePartOne")
    public ServerResponse addScorePartOne(HttpServletRequest request, @RequestBody String data) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        JSONObject jsonObject = JSON.parseObject(data);
        Integer num = jsonObject.getInteger("num");
        redisUtil.set(u.getId() + "addScorePartOne", num, 7200);
        return ServerResponse.createBySuccessMsg("成功提交步骤模块");
    }

    /**
     * U3D添加步骤模块(场景设置)
     *
     * @param request
     * @param
     * @return
     */
    @PostMapping(value = "/addScorePartTwo")
    public ServerResponse addScorePartTwo(HttpServletRequest request, @RequestBody String data) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        JSONObject jsonObject = JSON.parseObject(data);
        Integer num = jsonObject.getInteger("num");
        redisUtil.set(u.getId() + "addScorePartTwo", num, 7200);
        return ServerResponse.createBySuccessMsg("成功提交步骤模块");
    }

    /**
     * U3D添加步骤模块(直播中)
     *
     * @param request
     * @param
     * @return
     */
    @PostMapping(value = "/addScorePartThree")
    public ServerResponse addScorePartThree(HttpServletRequest request, @RequestBody String data) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        JSONObject jsonObject = JSON.parseObject(data);
        Integer num = jsonObject.getInteger("num");
        redisUtil.set(u.getId() + "addScorePartThree", num, 7200);
        return ServerResponse.createBySuccessMsg("成功提交步骤模块");
    }

    /**
     * 获取到U3D添加步骤模块
     *
     * @param request
     * @param
     * @return
     */
    @PostMapping(value = "/getScorePart")
    public ServerResponse<Object> getScorePart(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
/*        if(!jwt.equals(redisUtil.get(u.getId()+""))){
            return ServerResponse.createByAuthMsg("该账号已经在别处登录！");
        }*/
        ScorePart scorePart = new ScorePart();
        if (redisUtil.hasKey(u.getId() + "addScorePartOne")) {
            int appearancePart = (int) redisUtil.get(u.getId() + "addScorePartOne");
            scorePart.setAppearancePart(appearancePart);
        }
        if (redisUtil.hasKey(u.getId() + "addScorePartTwo")) {
            int sceneSettingPart = (int) redisUtil.get(u.getId() + "addScorePartTwo");
            scorePart.setSceneSettingPart(sceneSettingPart);
        }
        if (redisUtil.hasKey(u.getId() + "addScorePartThree")) {
            int livingBroadcastPart = (int) redisUtil.get(u.getId() + "addScorePartThree");
            scorePart.setLivingBroadcastPart(livingBroadcastPart);
        }
        return ServerResponse.createBySuccess(scorePart);
    }

    /**
     * @Author: liuzhaobo
     * @Description: 存储U3d实验步骤 展示 非提交
     * 1 拿到 token
     * 2 入库 用户id
     * @DateTime: 2022/9/20 0020 9:12
     * @Params:
     * @Return
     */
    @PostMapping("/submitStep")
    @ResponseBody
    public ServerResponse submitStep(@RequestBody String Data, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        try {
            JSONObject jsonObject = JSONObject.parseObject(Data);
            System.out.println("data"+Data);
            String steps = jsonObject.getString("steps");
            System.out.println(steps);
            //先查询 如果为 null 则添加 如果不为null 则 查询  +  更新
            Integer userid = u.getId();
            TmpU3d tmpU3d = tmpU3dServer.seletU3d(userid);
            List<Step> stepsList = JSON.parseArray(steps, Step.class);
            if (tmpU3d == null) {
                //没有则添加
                boolean updateU3d = tmpU3dServer.insertU3d(userid, steps);
                if (updateU3d) {
                    return ServerResponse.createBySuccessMsg("存储U3d内容成功");
                } else {
                    return ServerResponse.createByErrorMsg("存储U3d内容失败");
                }

            }
            if (tmpU3d != null) {
                //如果存在 将list映射对象 再 + 如 对象 list
                String step = tmpU3d.getStep();
                List<Step> stepList = JSON.parseArray(step, Step.class);

                //循环赋值

                for (Step st : stepsList
                ) {
                    stepList.add(st);

                }
                //拿到最终的 list 转string 进行更新
                String lastU3d = JSON.toJSONString(stepList);
                //update
                boolean updateU3d = tmpU3dServer.updateU3d(userid, lastU3d);
                if (updateU3d) {
                    return ServerResponse.createBySuccessMsg("存储U3d内容成功");
                } else {
                    return ServerResponse.createBySuccessMsg("存储U3d内容失败");
                }


            }
            return ServerResponse.createBySuccessMsg("存储U3d内容成功");
        } catch (Exception e) {
            e.printStackTrace();

            return ServerResponse.createByErrorMsg("存储U3d内容失败");
        }
    }

    /**
     * @Author: liuzhaobo
     * @Description: 查询 U3d List string
     * @DateTime: 2022/9/20 0020 13:58
     * @Params:
     * @Return
     */
    @PostMapping("/SelectOnceStep")
    @ResponseBody
    public ServerResponse SelectOnceStep(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            Integer userid = u.getId();
            String OneStep = tmpU3dServer.selectStepById(userid);
            JSONArray jsonArray = JSON.parseArray(OneStep);
            return ServerResponse.createBySuccess(jsonArray);
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("查询失败");
        }


    }
}
